﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

namespace Identity_Jwt_Demo.Controllers
{
    /// <summary>
    /// 授权管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AuthorizationController : ControllerBase
    {
        JwtSetings jwtSettings = null;
        public AuthorizationController(IOptions<JwtSetings> jwtSettings)
        {
            this.jwtSettings = jwtSettings.Value;
        }
        /// <summary>
        /// 获取Token
        /// </summary>
        /// <param name="appid">appid</param>
        /// <param name="appkey">appkey</param>
        /// <returns>jwtToken</returns>
        [HttpGet]
        public async Task<ActionResult> GetToken()
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, "张三"),
                new Claim("FullName", "老王家的张三"),
                new Claim(ClaimTypes.Role, "Administrator")
            };

            SigningCredentials credentials = null;
            if (jwtSettings.SecretKey == "DES")   //对称加密
            {
               var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey));
                credentials= new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            }
            else if (jwtSettings.SecretType == "RSA")   //非对称加密
            {
                var securityKey = new RsaSecurityKey(jwtSettings.PrivateRSA);
                credentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256Signature);
            }
             
            var token = new JwtSecurityToken(
                jwtSettings.Issuer,
                jwtSettings.Audience,
                claims,
                DateTime.Now,
                DateTime.Now.AddMinutes(jwtSettings.ExpireMinuters),
                credentials
                );
            return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
        }

        /// <summary>
        /// 获取密钥
        /// </summary>
        /// <returns>密钥</returns>
        [HttpGet]
        public async Task<ActionResult<string>> GetSecretKey()
        {
            return jwtSettings.SecretKey;
        }

        /// <summary>
        /// 获取登陆用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public Dictionary<string ,string > GetUserInfo()
        {
            var ret = new Dictionary<string, string>();
            foreach(var c in HttpContext.User.Claims)
            {
                ret.Add(c.Type, c.Value);
            }
            return ret;
        }

        /// <summary>
        /// 程序形式调用接口测试
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<string> Test()
        {
            var client = new System.Net.Http.HttpClient();
            client.BaseAddress = new Uri(Request.Scheme + "://" + Request.Host);
            var rsp = await client.GetAsync("/API/Authorization/GetToken");
            var tokenStr = await rsp.Content.ReadAsStringAsync();
            var token=Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(tokenStr);

            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token.token);
            rsp=await client.GetAsync("/API/Authorization/GetUserInfo");
            var userInfo = await rsp.Content.ReadAsStringAsync();
            return userInfo;

        }
    }
}